package com.cskaoyan.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.BaseBusinessException;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.constant.OrderRetCode;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.swing.text.Position;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {


    @Autowired
    StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    public boolean handle(TransHandlerContext context) {
        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        // 购物车中的商品数据
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();

        // 给context中的商品集合赋值
        List<Long> buyProductIds = createOrderContext.getBuyProductIds();

        if(CollectionUtils.isEmpty(buyProductIds)) {
            buyProductIds = new ArrayList<>();
            for (CartProductDto cartProductDto : cartProductDtoList) {
                buyProductIds.add(cartProductDto.getProductId());
            }
        }

        createOrderContext.setBuyProductIds(buyProductIds);

        // 锁定库存
        List<Stock> stocks = stockMapper.findStocksForUpdate(buyProductIds);

        // 判断库存是否初始化
        if (CollectionUtils.isEmpty(stocks)) {
            throw new BizException(OrderRetCode.ALL_PRODUCTS_STOCK_NOT_INIT.getCode(),
                    OrderRetCode.ALL_PRODUCTS_STOCK_NOT_INIT.getMessage());
        }

        if (stocks.size() != buyProductIds.size()) {
            throw new BizException(OrderRetCode.PART_OF_PRODUCTS_STOCK_NOT_INIT.getCode(),
                    OrderRetCode.PART_OF_PRODUCTS_STOCK_NOT_INIT.getMessage());
        }

        // 扣减库存
        for (CartProductDto cartProductDto : cartProductDtoList) {

            Stock stock1 = stockMapper.selectStockForUpdate(cartProductDto.getProductId());


            // 判断是否超出限购数量

            if(cartProductDto.getProductNum() > stock1.getRestrictCount()) {
                // 抛出异常，事务回滚
                throw new BizException(OrderRetCode.ITEM_OUT_LIMIT.getCode(),
                        OrderRetCode.ITEM_OUT_LIMIT.getMessage());
            }

            Long stockCount = stock1.getStockCount();

            if(cartProductDto.getProductNum() > stockCount) {
                throw new BizException(OrderRetCode.ITEM_NOT_ENOUGH.getCode(),
                        OrderRetCode.ITEM_NOT_ENOUGH.getMessage());
            }

            // 扣减库存
            Stock stock = new Stock(cartProductDto.getProductId(),
                    -(cartProductDto.getProductNum()),
                    cartProductDto.getProductNum().intValue());
            stockMapper.updateStock(stock);

        }
        return true;
    }
}